package com.rtsapp.server.platform.facebook;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.rtsapp.server.app.AppConfig;
import com.rtsapp.server.logger.Logger;
import com.rtsapp.server.logger.LoggerFactory;
import com.rtsapp.server.platform.IPlatformLoginService;

import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


/**
 * Facebook 登陆验证
 *
 * 官方文档:
 *
 * https://developers.facebook.com/docs/facebook-login/manually-build-a-login-flow#checktoken
 *
 * 基本流程
 *
 * GET graph.facebook.com/debug_token?input_token={token-to-inspect}&access_token={app-token-or-admin-token}
 *  input_token = 要检查的口令
 *  access_token= 应用访问口令,或者应用开发者的访问口令
 *
 *  access_token 可以动态获取或者使用另一种形式 appid|app_secret
 *
 *  使用动态获取目前对获取的token有效时常不确定,所以暂时使用后一种方式,如果后一种方式无效则必须使用第一种方式.
 *
 *  动态获取地址:
 *
 *  GET /oauth/access_token?client_id={app-id}&client_secret={app-secret}&grant_type=client_credentials
 *
 */
public class FacebookPlatformLoginService implements IPlatformLoginService {

    private static final Logger LOGGER = LoggerFactory.getLogger( FacebookPlatformLoginService.class );

    //    https://graph.facebook.com/debug_token?input_token=%s&access_token=%s
    private static final String FACEBOOK_VERIFY_URL = AppConfig.getInstance().getFaceBookUrl();

    private static final String FACEBOOK_SECRET = AppConfig.getInstance().getFacebookAppId() + "|" + AppConfig.getInstance().getFacebookAppSecret();

//   动态获取密匙的方式
//    private static final String FACEBOOK_TOKEN_URL = "https://graph.facebook.com/oauth/access_token?client_id=287241104993160&client_secret=61e82ff9ca6b1e2df0e6bbac0e66178f&grant_type=client_credentials";

//    private static String FACEBOOK_APP_ACCESS_TOKEN = null;

//    static {
//
//        try {
//
//            String accessToken = httpGet(FACEBOOK_TOKEN_URL);
//            FACEBOOK_APP_ACCESS_TOKEN = accessToken.split("=")[1];
//
//        } catch (IOException e) {
//            LOGGER.error("获取Facebook应用访问密匙出现异常",e);
//            System.exit(0);
//        }
//
//
//    }

    @Override
    public String validateLoginToken(String token, String uid) {

        if ( token == null ) {
            return null;
        }

        LOGGER.info( "facebook 登录 sdk_token: " + token );

        String result = null;

        try {
            String url = String.format(FACEBOOK_VERIFY_URL,URLEncoder.encode(token,"utf-8"),URLEncoder.encode(FACEBOOK_SECRET,"utf-8"));
            result = httpGet(url);
            LOGGER.info("Facebook 登录:返回校验数据 "+ result);

            JSONObject jsonObject = JSON.parseObject(result);
            JSONObject dataObject = jsonObject.getJSONObject("data");

            result = dataObject.getString("user_id");
        } catch (Exception e) {
            LOGGER.error("Facebook 登录: 请求验证时返回错误",e);
            return null;
        }

        return result;
    }

    public static String httpGet(String url) throws IOException
    {
        if (null == url || url.isEmpty())
        {
            return "";
        }
        HttpGet httpGet = new HttpGet(url);
        System.out.println(url);
        // 设置超时时间为3s
        RequestConfig config = RequestConfig.custom().setSocketTimeout(3000).setConnectTimeout(3000).setAuthenticationEnabled(false).build();
        httpGet.setConfig(config);

        // 准备环境
        try (CloseableHttpClient http = HttpClients.createDefault(); CloseableHttpResponse response = http.execute(httpGet);)
        {
            // 返回内容
            HttpEntity entity = response.getEntity();
            // 主体数据
            InputStream in = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, "UTF-8"));
            // 读取
            StringBuilder sb = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
            {
                sb.append(line);
            }
            return sb.toString();
        }
    }

    public static void main(String[] args) throws UnsupportedEncodingException {

        String token = "EAAEFPogHK4gBAOwgP8pflZAZCItcgQPecwlymJOiff1EZCqGEmWI0S8ZBdNOOsV8jVBdG8Mml7NmoMBAgNnIkd4v6K5x3TJhLBZCh2lcZCygtW1jSZAgTAyOeIaZBZAddjjW8LudrAngrWXOZAIhrZBhPHT2lbjMyAkdlcnOZCtiFelfPA5c2XCYCIFcfvW3p04QtPkrDcTVHG3z8QZDZD";
        FacebookPlatformLoginService facebookPlatformLoginService = new FacebookPlatformLoginService();
        String result = facebookPlatformLoginService.validateLoginToken(token, "");
        System.out.println(result);


    }
}
